package org.whatever.aha.zjut.platform.service.school;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.w3c.dom.ls.LSException;
import org.whatever.aha.zjut.base.constant.StatusConstant;
import org.whatever.aha.zjut.platform.entity.User;
import org.whatever.aha.zjut.platform.entity.school.JudgeProjectDistribution;
import org.whatever.aha.zjut.platform.entity.school.ProjectScore;
import org.whatever.aha.zjut.platform.mapper.school.JudgeProjectDistributionMapper;
import org.whatever.aha.zjut.platform.service.UserService;
import org.whatever.aha.zjut.platform.service.competition.CompetitionService;
import org.whatever.aha.zjut.platform.service.project.ProjectService;
import org.whatever.aha.zjut.platform.vo.school.ProjectArrangementVo;
import org.whatever.aha.zjut.platform.vo.school.TagInfoVo;

import java.util.*;
import java.util.stream.Collectors;

/**
 * @author Vc
 * @version 1.0
 * @Desc 评审项目分配记录表
 * @date 2021/11/21 18:47
 */
@RequiredArgsConstructor
@Service
public class JudgeProjectDistributionService {
    final JudgeProjectDistributionMapper judgeProjectDistributionMapper;
    final CompetitionService competitionService;
    final UserService userService;
    final ProjectService projectService;
    final ProjectScoreService projectScoreService;

    /**
     * 增加一条项目评委
     *
     * @param judgeProjectDistribution
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int addJudgeProjectDistribution(JudgeProjectDistribution judgeProjectDistribution){
        return judgeProjectDistributionMapper.insert(judgeProjectDistribution);
    }

    /**
     * 根据竞赛Id删除项目评委评审信息（删除项目用）
     *
     * @param compId
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int deleteJudgeProjectDistributionByCompId(int compId){
        return judgeProjectDistributionMapper.delete(new QueryWrapper<JudgeProjectDistribution>().eq("comp_id",compId));
    }

    /**
     * 指派评审赛事
     *
     * @param userId
     * @param compId
     * @param tag
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int arrangeProject(int userId, int compId, int stageId, String tag){
        User userById = userService.getUserById(userId);
        //评委评审多个组别使用-分割
        String[] splits = tag.split("-");
        for(String split : splits){
            JudgeProjectDistribution judgeProjectDistribution = JudgeProjectDistribution.builder().compId(compId)
                    .tag(split)
                    .stageId(stageId)
                    .ddl(userById.getUntieTime())
                    .judgeId(userId)
                    .build();
            judgeProjectDistributionMapper.insert(judgeProjectDistribution);
        }
        return splits.length;
    }

    /**
     * 项目评审分配概览
     *
     * @param compId
     * @return
     */
    public List<ProjectArrangementVo> projectArrangement(int compId){
        Integer stageId = competitionService.getStageIdByTime(compId);
        List<ProjectArrangementVo> projectArrangementVoList = new ArrayList<>();
        List<JudgeProjectDistribution> judgeProjectDistributions = judgeProjectDistributionMapper.selectList(new QueryWrapper<JudgeProjectDistribution>().eq("comp_id", compId).eq("stage_id", stageId).orderByAsc("tag", "ddl"));
        for (JudgeProjectDistribution judgeProjectDistribution : judgeProjectDistributions) {
            ProjectArrangementVo projectArrangementVo = new ProjectArrangementVo();
            projectArrangementVo.setTag(judgeProjectDistribution.getTag());
            projectArrangementVo.setDdl(judgeProjectDistribution.getDdl());
            User judgeInfo = userService.getUserById(judgeProjectDistribution.getJudgeId());
            projectArrangementVo.setUsername(judgeInfo.getUsername());
            projectArrangementVo.setPhone(judgeInfo.getPhoneNumber());
            projectArrangementVo.setUserId(judgeProjectDistribution.getJudgeId());

            //获得已完成评审项目数
            projectArrangementVo.setAlreadyRecNum(projectScoreService.getAlreadyJudgeNum(stageId, judgeProjectDistribution.getJudgeId(), judgeProjectDistribution.getTag()));
            //获得应评审项目总数
            projectArrangementVo.setTaskNum(projectService.getJudgeTaskNum(compId, stageId, judgeProjectDistribution.getTag()));
            projectArrangementVoList.add(projectArrangementVo);
        }
        return projectArrangementVoList;
    }

    /**
     * 获取未被分配的组别信息
     *
     * @param compId
     * @return
     */
    public List<TagInfoVo> getUnArrangeTagInfo(int compId){
        List<TagInfoVo> tagInfoVoList= new ArrayList<>();
        Integer stageId = competitionService.getStageIdByTime(compId);
        //获取所有不是省级推荐、不是自评三等奖的Tag
        List<String> projectTags = projectService.getProjectsByStageId(stageId).stream()
                .filter(project -> {
                    return !project.getProjectProvinceRec() && !StatusConstant.PROJECT_AWARD_ACADEMY_THIRD_PRIZE.getCode().equals(project.getProjectAwardId());
                })
                .map(project -> project.getProjectTag()).distinct().collect(Collectors.toList());
        //获取已评审Tag
        List<JudgeProjectDistribution> judgeProjectDistributions = judgeProjectDistributionMapper.selectList(new QueryWrapper<JudgeProjectDistribution>().eq("comp_id", compId).eq("stage_id", stageId));
        List<String> judgedProjectIds = judgeProjectDistributions.stream().map(judgeProjectDistribution -> judgeProjectDistribution.getTag()).distinct().collect(Collectors.toList());
        projectTags.removeAll(judgedProjectIds);

        for(String tag : projectTags){
            tagInfoVoList.add(new TagInfoVo(tag, projectService.getJudgeTaskNum(compId, stageId, tag)));
        }
        return tagInfoVoList;
    }

    /**
     * 删除评委指派信息（删除评委）
     *
     * @param userId
     * @return
     */
    @Transactional(rollbackFor = Exception.class, propagation = Propagation.REQUIRED)
    public int deleteJudgeAccount(int userId){
        judgeProjectDistributionMapper.delete(new QueryWrapper<JudgeProjectDistribution>().eq("judge_id",userId));
        return userService.deleteJudgeAccount(userId);
    }

    /**
     * 根据竞赛阶段和评委Id唯一键获取该评委已指派的Tag
     *
     * @param compId
     * @param stageId
     * @param userId
     * @return
     */
    public List<Object> getTagsByCompIdAndStageIdAndJudgeId(int compId, int stageId, int userId){
        return judgeProjectDistributionMapper.selectObjs(new QueryWrapper<JudgeProjectDistribution>().eq("comp_id", compId).eq("stage_id", stageId).eq("judge_id", userId).select("tag"));
    }

    /**
     * 根据评委Id获取需要评审的竞赛Id信息
     *
     * @param judgeId
     * @return
     */
    public List<JudgeProjectDistribution> getJudgeProjectDistributionByJudgeId(int judgeId){
        return judgeProjectDistributionMapper.selectList(new QueryWrapper<JudgeProjectDistribution>().eq("judge_id", judgeId));
    }
}
